<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        background-color: #333;
      }
    </style>
  </head>
  <body>
    <script>
      const obj = {
        title: 'hello',
        age: 18,
      };

      Object.freeze(obj);

      const objProxy = new Proxy(obj, {
        get(target, key, receiver) {
          return target[key];
        },
        set(target, key, newValue, receiver) {
          //   // 还是在直接操作原对象
          //   target[key] = newValue;

          // 代理对象的目的:不再直接操作原对象
          const isSuccess = Reflect.set(target, key, newValue);
          if (!isSuccess) throw new Error('设置失败');
        },
      });

      console.log(objProxy.title);

      try {
        objProxy.title = 'world';
      } catch (error) {
        console.log(error);
      }

      console.log(objProxy.title);
    </script>
  </body>
</html>
